import TRTCEvent from './TRTCEvent';

let self;
let callback;
const eventMap = new Map();
export default class TRTCSocket {
  /**
   * 初始化连接服务器
   */
  constructor(url, producerOnline, producerOffline) {
    this.messageId = 0;
    this.webSocket = new WebSocket(url);
    this.webSocket.onclose = this.onClose;
    this.webSocket.onmessage = this.onMessage;
    this.webSocket.onerror = this.onError;
    this.webSocket.onopen = this.onOpen;

    this.producerOnline = producerOnline;
    this.producerOffline = producerOffline;

    this.timeOut = 3000;
    this.timeObj = null;
    this.serverTimeObj = null;
    this.retry = 5;
    self = this;
  }

  /**
   * 监听消息
   * @param message
   */
  // eslint-disable-next-line class-methods-use-this
  onMessage(messageEvent) {
    // console.log('messageEvent=========', messageEvent);
    self.startHeart();
    if (messageEvent.data === 'pong') {
      return;
    }
    const message = JSON.parse(messageEvent.data);
    console.log('message=========', message);
    // 没有消息id
    if (
      message.header === undefined ||
      message.header === '' ||
      message.header === null
    ) {
      // 判断是否是服务器主动消息
      switch (message.event) {
        case 'producerOffline':
          console.log('推流人下线');
          self.producerOffline(message.mediaData);
          break;
        case 'producerOnline':
          console.log('推流人上线');
          self.producerOnline(message.mediaData);
          break;
        default:
      }
      return;
    }
    // eslint-disable-next-line radix
    const header = parseInt(message.header);
    if (!eventMap.has(header)) {
      // 消息没有对应的方法处理
      console.log('没有找到回调方法');
      return;
    }
    const trtcEvent = eventMap.get(header);
    try {
      trtcEvent.runCallback(message, trtcEvent.message);
    } catch (e) {
      console.log('事件回调执行失败: ', e);
      trtcEvent.runErrBack(message, trtcEvent.message);
    } finally {
      eventMap.delete(header);
    }
  }

  /**
   * 监听错误
   */
  // eslint-disable-next-line class-methods-use-this
  onError(error) {
    console.log(error);
  }

  /**
   * 监听接入
   */
  // eslint-disable-next-line class-methods-use-this
  onOpen() {
    console.log('连接成功');
    self.startHeart();

    callback(true);
  }

  /**
   * 监听关闭
   */
  // eslint-disable-next-line class-methods-use-this
  onClose() {
    console.log('连接断开');
    // callback(false);
  }

  /**
   * 关闭通信长连接
   */
  closeSocket() {
    this.webSocket.close();
  }

  /**
   * 发送消息
   */
  sendMessage(message, callback, errback) {
    // eslint-disable-next-line no-plusplus
    const messageId = this.messageId++;
    // eslint-disable-next-line no-param-reassign
    message.header = messageId;
    const trtcEvent = new TRTCEvent(message, callback, errback);
    console.log(trtcEvent.getMessage());
    eventMap.set(messageId, trtcEvent);
    console.log('发送消息data====', message);
    this.webSocket.send(JSON.stringify(message));
  }

  /**
   * 心跳
   */
  startHeart() {
    // 清除延时器
    // eslint-disable-next-line no-unused-expressions
    this.timeObj && clearTimeout(this.timeObj);
    // eslint-disable-next-line no-unused-expressions
    this.timeObj = setTimeout(() => {
      self.webSocket.send('ping');
      // console.log('发送了==========ping')
    }, this.timeOut);
  }
  is_Socket_state(callBack) {
    callback = callBack;
  }
}
